/*
 * @Author: Mr.Cong Wei
 * @Date: 2022-12-19 13:47:01
 * @LastEditTime: 2022-12-19 18:00:46
 */
/**
 * 分页
 *
 * 1.将一个table拆分多个table（只有第一个有表头），每个table高度为一页纸张
 * 2.格外处理单元格合并的情况
 *
 * */
import domtoimage from 'dom-to-image'
import print from 'print-js'
import 'print-js/dist/print.css'
interface PrintTableOption {
  rootDom: HTMLElement
  title?: string
}
export class PrintTable {
  rootDom: HTMLElement
  title?: string
  __origntDom__: HTMLElement // 原始数据
  __flag__: boolean = true // 节流阀
  __FIRST_PAGE__ = true // 第一页
  onFinish?: () => void
  constructor(_option: PrintTableOption) {
    this.__origntDom__ = _option.rootDom
    this.title = _option.title
    // this.init();
  }
  async print() {
    if (this.__flag__) {
      this.__flag__ = false
      //   生成图片
      //   debugger;
      //   debugger;
      try {
        const blob = await domtoimage.toBlob(this.__origntDom__)
        //   将图片转为DateUrl
        const fr = new FileReader()
        fr.onload = e => {
          print({
            printable: e.target.result,
            type: 'image',
            scanStyles: false,
            documentTitle: this.title,
            header: this.title,
            headerStyle: 'font-weight: 400; text-align:center;font-size:18px'
          })
          this.__flag__ = true
        }

        fr.readAsDataURL(blob)
      } catch {}
    }
  }
  init() {
    const height = 800 // 每页高度
    let pageTotalheight = 0
    // 根table节点
    const tableEle = this.createTableEle(this.__origntDom__)
    // 初始化根节点
    this.rootDom = document.createElement('div')
    this.rootDom.id = 'tableId'

    for (const _e of this.__origntDom__.children) {
      if (_e.children.length === 1) {
        // 存在单元格合并情况
      } else {
        if (pageTotalheight + _e.scrollHeight > height) {
          pageTotalheight = 0
          tableEle
          // 超出一页
        } else {
          // 未超出一页
          pageTotalheight += _e.scrollHeight
        }
      }
    }
  }
  createTableEle(refer) {
    const tableEle = document.createElement('table')
    tableEle.classList.add(...refer.classList)
    return tableEle
  }
}
